package com.wang.controller;

import com.wang.entity.User;
import com.wang.validator.EmailValidator;
import com.wang.validator.UserValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.Valid;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Classname ValidatorController
 * @Description TODO
 * @Date 2024/5/21 9:59
 * @Created by pc
 */
@Controller
public class ValidatorController {
    @Autowired
    private EmailValidator emailValidator;
    @Autowired
    private UserValidator userValidator;

    // 接受参数  自定编辑器
    @InitBinder
    public void dataBinding(WebDataBinder binder){
        binder.addValidators(emailValidator,userValidator);
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        df.setLenient(false);
        binder.registerCustomEditor(Date.class,"birthday",new CustomDateEditor(df,true));
    }

    @ResponseBody
    @RequestMapping("/user")
    public String testUser(@RequestBody @Valid User user, BindingResult result){
        if(result.hasErrors()){
            return result.getAllErrors().get(0).getDefaultMessage();
        }
        System.out.println("name:"+user.getName());
        System.out.println("email:"+user.getEmail());
        System.out.println("birthday:"+user.getBirthday());
        return "success";
    }
}
